package test5;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerDemo {
    /*
    需求：将文件上传到指定IP的主机。
        1. TCP的服务端可以接受多个客户端的连接
        2. TCP的客户端上传文件到服务器端
        3. 文件保存到 c:/java/file 文件下，文件名随机生成，只要不出现文件覆盖即可。
        4. 服务器端需要反馈上传状态(成功或失败)给客户端。
     */
    public static void main(String[] args) throws IOException {
        ExecutorService service = Executors.newCachedThreadPool();
        ServerSocket ss = new ServerSocket(8888);
        while (true) {
            Socket accept = ss.accept();
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream is = accept.getInputStream();
                        BufferedInputStream bis = new BufferedInputStream(is);
                        String fileName = "D:\\Develop\\workSpace\\internet-test\\src\\" + System.currentTimeMillis() + ".txt";
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
                        int b;
                        while ((b = bis.read()) != -1) {
                            bos.write(b);
                        }
                        bos.close();

                        OutputStream os = accept.getOutputStream();
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                        String message = "传输成功";
                        bw.write(message);
                        bw.flush();

                        accept.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });


        }

    }
}
